'use strict'
import { getLength } from './utils'

let watermark = {}

let setWatermark = (str, el) => {
  let id = '1.23452384164.123412415'
  let parentEL = el || document.body

  if (document.getElementById(id) !== null) {
    parentEL.removeChild(document.getElementById(id))
  }
  console.log('parentEL: ', parentEL)
  let can = document.createElement('canvas')

  // let fontSize = 20 * window.devicePixelRatio
  let fontSize = 20
  let fontWidth = Math.ceil(getLength(str) / 2 + 4) * fontSize
  can.width = Math.cos((45 * Math.PI) / 180) * fontWidth
  can.height = Math.sin((45 * Math.PI) / 180) * fontWidth

  let cans = can.getContext('2d')
  cans.font = `${fontSize}px sans-serif`
  cans.fillStyle = 'rgba(7, 40, 57, 0.15)'
  cans.textWeight = '600'
  cans.textAlign = 'left'
  cans.textBaseline = 'Middle'
  // cans.translate(45, can.height)
  cans.translate(10, can.height - 16)
  cans.rotate((-45) * Math.PI / 180)
  cans.fillText(str, 0, 0)

  let div = document.createElement('div')
  div.id = id
  div.style.pointerEvents = 'none'
  div.style.top = '0px'
  div.style.left = '0px'
  div.style.position = 'absolute'
  div.style.zIndex = '1000'
  div.style.width = parentEL.offsetWidth + 'px'
  div.style.height = parentEL.offsetHeight + 'px'
  let img = new Image()
  img.src = can.toDataURL('image/png')
  div.style.background =
    'url(' + can.toDataURL('image/png') + ') left top repeat'
  parentEL.appendChild(div)
  return id
}

// 该方法只允许调用一次
watermark.set = (str, el) => {
  // let id = setWatermark(str, el)
  // setInterval(() => {
  //   if (document.getElementById(id) === null) {
  //     id = setWatermark(str, el)
  //   }
  // }, 500)
  window.onresize = () => {
    setWatermark(str, el)
  }
  setWatermark(str, el)
  setTimeout(() => {
    setWatermark(str, el)
  }, 1000)
}

export default watermark
